/**
 * @Descripttion: app检查更新
 * @Version: 1.0.0
 * @Author: leefine
 */

import config from '@/upgrade-config.js'
import appDialog from './dialog'
const {
	timer = 24
} = config.upgrade;

class CheckUpate {
	// 判断时间戳检测是否更新
	judgeTimeStamp() {
		uni.getStorage({
			key: 'appUpdateTime',
			success: (res) => {
				const timeLength = 1000 * 60 * 60 * timer;
				const currTimeStamp = new Date().getTime();
				if ((res.data + timeLength) < currTimeStamp) {
					this.getVersion();
				}
			},
			fail: () => {
				// 获取缓存失败(第一次进入APP)检测更新
				this.getVersion();
			}
		})
	}

	// 获取当前版本信息
	getVersion() {
		this.setDefaultIcon();
		plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
			CheckUpate.getUrl(wgtinfo.versionCode).then(res => {
				/* 
				res.status 是否有新版本，0无，1有
				res.path 新版 apk 地址
				res.changelog 更新日志
				 */
				if (res.status === 1) {
					const path = res.path || '';
					const changeLog = res.changelog || '';
					appDialog.show(path, changeLog);
				}
			})
			this.storageTimeStamp()
		});
	}

	// 缓存检测更新的时间戳
	storageTimeStamp() {
		const currTimeStamp = new Date().getTime();
		uni.setStorage({
			key: 'appUpdateTime',
			data: currTimeStamp
		})
	}

	setDefaultIcon() {
		var bitmap = new plus.nativeObj.Bitmap('upgrade_default');
		var imageStr =
			'';

		bitmap.loadBase64Data(imageStr, function() {
			bitmap.save("_pic/upgrade.png", {}, function(i) {
				bitmap.clear();
			}, function(e) {
				bitmap.clear();
			});
		}, function() {
			bitmap.clear();
		});
	}
}

// type检测类型:0自动检测,1用户主动检测
export default function(fn, type = 0) {
	const cu = new CheckUpate()
	if (type == 1) {
		cu.getVersion();
	} else {
		cu.judgeTimeStamp();
	}
	CheckUpate.getUrl = fn;
}
